package com.aids_malaria.ui.datacollect;

import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.aids_malaria.R;
import com.aids_malaria.app.Constant;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.db.DBManager;
import com.aids_malaria.helper.PointLengthFilter;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.AreaC;
import com.aids_malaria.http.response.AreaV;
import com.aids_malaria.util.AppUtil;
import com.aids_malaria.util.DisplayUtil;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.LogUtil;
import com.aids_malaria.util.ResourceUtil;
import com.aids_malaria.util.SpUtil;
import com.aids_malaria.util.StringUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.dialog.ConfirmDialog;
import com.aids_malaria.widget.titlebar.TitleBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class VillageDataCreateEditActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.et_county_name)
    EditText et_county_name;
    @BindView(R.id.et_village_name)
    EditText et_village_name;
    @BindView(R.id.et_coordinate_x)
    EditText et_coordinate_x;
    @BindView(R.id.et_coordinate_y)
    EditText et_coordinate_y;

    public static final String KEY_IS_CREATE = "is_create";
    public static final String KEY_AREAC = "areaC";
    public static final String KEY_AREAV = "areaV";

    private boolean isCreate;
    private AreaC mAreaC;
    private AreaV mAreaV;
    private String countyCode;

    private String preVillageName;
    private String preX;
    private String preY;



    @Override
    protected int getLayoutId() {
        return R.layout.activity_village_data_create_edit;
    }

    @Override
    protected void initData() {
        super.initData();
        PointLengthFilter pointLengthFilter = new PointLengthFilter(6);
        et_coordinate_x.setFilters(new InputFilter[]{pointLengthFilter});
        et_coordinate_y.setFilters(new InputFilter[]{pointLengthFilter});

        et_coordinate_x.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        et_coordinate_y.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        Bundle bundle = getIntent().getExtras();
        if(null != bundle){
            isCreate = bundle.getBoolean(KEY_IS_CREATE);
            mAreaV = new AreaV();
            mAreaV.setCounty_code("");
            mAreaV.setVillage_code("");
            mAreaV.setVillage_name("");
            mAreaV.setX("");
            mAreaV.setY("");
        }
        if(isCreate){
            initTitleBar(title_bar,getString(R.string.administrative_village_create));
            mAreaC = (AreaC) bundle.getSerializable(KEY_AREAC);
            et_county_name.setText(mAreaC.getCounty_name());
            countyCode = mAreaC.getCounty_code();
        }else{
            initTitleBar(title_bar,getString(R.string.administrative_village_edit));
            mAreaV = (AreaV) bundle.getSerializable(KEY_AREAV);
            et_county_name.setText(mAreaV.getCounty_name());
            et_village_name.setText(mAreaV.getVillage_name());
            et_coordinate_x.setText(mAreaV.getX());
            et_coordinate_y.setText(mAreaV.getY());

            //记录修改前的数据
            preVillageName = mAreaV.getVillage_name();
            preX = mAreaV.getX();
            preY = mAreaV.getY();

            countyCode = mAreaV.getCounty_code();
        }

    }

    @Override
    public void back() {
        String countyName = et_county_name.getText().toString().trim();
        String villageName = et_village_name.getText().toString().trim();
        String coordinateX = et_coordinate_x.getText().toString().trim();
        String coordinateY = et_coordinate_y.getText().toString().trim();

        Boolean showTip =(  (isCreate && ( !TextUtils.isEmpty(villageName)
        || !TextUtils.isEmpty(coordinateX)) || TextUtils.isEmpty(coordinateY) ) ||
                (!isCreate && (!villageName.equals(preVillageName) || !coordinateX.equals(preX)
                        || !coordinateY.equals(preY)) ));
        if (!showTip){finish();return;}

        String tipString = isCreate ? getString(R.string.tip_data_add):getString(R.string.tip_data_modify);
        ConfirmDialog.newInstance(true, getString(R.string.hint), tipString)
                .setCancelConfirOption(new ConfirmDialog.CancelConfirOption() {
                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void confirm() {
                        finish();
                    }
                })
                .setOutCancel(true)
                .setWidth(DisplayUtil.px2dp((int) (DisplayUtil.getWindowWidth() * 0.5)))
                .show(getSupportFragmentManager());
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @OnClick({R.id.tv_gain_coordinate,R.id.tv_confirm})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.tv_gain_coordinate:
                getLocation();
                break;
            case R.id.tv_confirm:
                String countyName = et_county_name.getText().toString().trim();
                String villageName = et_village_name.getText().toString().trim();
                String coordinateX = et_coordinate_x.getText().toString().trim();
                String coordinateY = et_coordinate_y.getText().toString().trim();
                if(StringUtil.isEmpty(countyName) || StringUtil.isEmpty(villageName) ||
                    StringUtil.isEmpty(coordinateX) || StringUtil.isEmpty(coordinateY)){
                    ToastUtil.showToast(getString(R.string.input_null));
                    return;
                }
                mAreaV.setCounty_name(countyName);
                mAreaV.setCounty_code(countyCode);
                mAreaV.setVillage_name(villageName);
                mAreaV.setX(coordinateX);
                mAreaV.setY(coordinateY);
                if(isOnLine()){
                    String dataJson = GsonUtil.beanToJson(mAreaV);
                    LogUtil.d("dataJson:------------" + dataJson);
                    if(isCreate){
                        saveVillage("1", dataJson);
                    }else{
                        saveVillage("2", dataJson);
                    }
                }else{
                    LogUtil.d("mAreaV:"+GsonUtil.beanToJson(mAreaV));
                    if(isCreate){
                        //判断village_name是否重复
                        List<AreaV> byVillageNameList = DBManager.get().areaVDao().getByVillageNameAndCountyCode(villageName, countyCode);
                        if(byVillageNameList.size() > 0){
                            //有数据代表该县下存在该村名
                            ToastUtil.showToast(ResourceUtil.getString(R.string.village_name_had_repeat));
                            return;
                        }
                        //获取最大village_code + 1
                        String maxVillageCode = "";
                        List<AreaV> areaVList = DBManager.get().areaVDao().getAllByCountyCode(countyCode);
                        if(null != areaVList && areaVList.size() > 0){
                            LogUtil.d("areaVList:"+GsonUtil.beanToJson(areaVList));
                            //village_code转整形
                            List<Integer> villageCodeList = new ArrayList<>();
                            for (AreaV arecV : areaVList) {
                                villageCodeList.add(Integer.valueOf(arecV.getVillage_code()));
                            }
                            Integer maxVillageCodeInt = villageCodeList.stream().reduce(Integer::max).get();
                            maxVillageCode = String.valueOf(maxVillageCodeInt + 1);
                        }else{
                            maxVillageCode = countyCode + "0001";//eg:10001
                        }
                        LogUtil.d("maxVillageCode:"+maxVillageCode);
                        mAreaV.setVillage_code(maxVillageCode);
                        mAreaV.setCreateOrUpdate(true);
                        mAreaV.setBusyType("1");
//                        LiteOrmUtil.getLiteOrm().insert(mAreaV);
                        DBManager.get().areaVDao().insert(mAreaV);
                    }else{
                        mAreaV.setCreateOrUpdate(!villageName.equals(preVillageName) || !coordinateX.equals(preX)
                        || !coordinateY.equals(preY));
                        mAreaV.setBusyType("2");
                        mAreaV.setCreateOrUpdate(true);
//                        LiteOrmUtil.getLiteOrm().update(mAreaV);
                        DBManager.get().areaVDao().update(mAreaV);
                    }
                    ToastUtil.showToast(getString(R.string.operate_success));
                    finish();
                }
                break;
        }
    }

    private LocationManager locationManager;
    private String provider = "";
    private LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            getLoadingDialog().dismiss();
            et_coordinate_x.setText(String.format("%.6f", location.getLongitude()));
            et_coordinate_y.setText(String.format("%.6f", location.getLatitude()));
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
            getLoadingDialog().dismiss();
        }

        @Override
        public void onProviderEnabled(String s) {
            getLoadingDialog().dismiss();
        }

        @Override
        public void onProviderDisabled(String s) {
            getLoadingDialog().dismiss();
        }
    };
    /**
     * 获取定位
     */
    @SuppressLint("MissingPermission")
    private void getLocation() {
        getLoadingDialog().show();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providerList = locationManager.getProviders(true);
        if (providerList.contains(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else {
            ToastUtil.showToast("No location provider to use");
        }
        Location location = locationManager.getLastKnownLocation(provider);
        if(location !=null){
            getLoadingDialog().dismiss();
            et_coordinate_x.setText(String.format("%.6f", location.getLongitude()));
            et_coordinate_y.setText(String.format("%.6f", location.getLatitude()));
        }
        locationManager.requestLocationUpdates(provider, 5000, 1, locationListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(locationManager!=null){
            locationManager.removeUpdates(locationListener);
        }
    }

    /**
     * 保存行政村数据
     * @param busy_type  保存类型 1插入 2更改 3 删除
     * @param data  data(各数据字段定义见数据库TBL_COM_AREAV表定义)： 该用户数据（json格式）
     * @return
     */
    private void saveVillage(String busy_type, String data) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data);
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).saveVillage(busy_type, requestBody)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<Object>() {

                    @Override
                    protected void onStart() {

                    }

                    @Override
                    protected void onSuccess(Object data) throws Exception {
                        ToastUtil.showToast(getString(R.string.operate_success));
                        finish();
                    }

                    @Override
                    protected void onFinish() {

                    }
                });
    }

}
